
package uk.ac.cam.cl.oscar.edgefinder;

import java.awt.image.BufferedImage;
import java.awt.Point;
import java.util.*;

public class ImageRaytracer {

	public static RayPackage raytrace (BufferedImage image) {
	
		RayPackage rp = new RayPackage();
			
		double rayRes = 400;
		double raySep = 2.0;
	
		for (double y = 0; y < image.getHeight(); y += image.getHeight()-1) 
		{
			double dx = 0;
			double dy = 2*(((double)image.getHeight()/2) - y - 0.01)/rayRes;
		
			for (double x = 0; x < image.getWidth(); x+=raySep) 
			{
				double tx = (double)x;
				double ty = (double)y;
				
				for (int i = 0; i < rayRes; i++) {
					int rx = (int)Math.round(tx);
					int ry = (int)Math.round(ty);
			
					int sample = image.getRGB (rx, ry) & 0xFF;

					if (sample > 30) {
						Point p = new Point();
						p.x = (int)rx;
						p.y = (int)ry;
						
						if (y < image.getHeight()/2) {
							((List<Point>)rp.points[0]).add (p);
						}
						else ((List<Point>)rp.points[2]).add (p);
						
						break;
					}
					tx = x + ((double)i)*dx;
					ty = y + ((double)i)*dy;
				}
			}
		}
		
		for (double x = 0; x < image.getWidth(); x += image.getWidth()-1) 
		{
			double dx = 2*(((double)image.getWidth()/2) - x - 0.01)/rayRes;;
			double dy = 0;
		
			for (double y = 0; y < image.getHeight(); y+=raySep) 
			{
				double tx = (double)x;
				double ty = (double)y;
							
				for (int i = 0; i < rayRes; i++) {
					int rx = (int)Math.round(tx);
					int ry = (int)Math.round(ty);
					int sample = image.getRGB (rx, ry) & 0xFF;
					
					if (sample > 30) {
						Point p = new Point();
						p.x = (int)rx;
						p.y = (int)ry;
						
						if (x < image.getWidth()/2) {
							((List<Point>)rp.points[1]).add (p);
						}
						else ((List<Point>)rp.points[3]).add (p);
						
						break;
					}
					tx = x + ((double)i)*dx;
					ty = y + ((double)i)*dy;
				}
			}
		}
		return rp;
	}
}